#coding=utf-8
'''
Created on Jun 18, 2011
@author: liyinhui
@moduleName: web.tools
@description: 通用工具脚本
'''
import httplib
import json
import hashlib, time
import cStringIO
import urllib


import Image, ImageDraw, ImageFont, random 
from datetime import datetime

from constants import FONT_FILE as _font_file

def build_verify_code():
    '''
    验证码生成函数,返回验证码和图片
    '''
    IMG_W = 80
    IMG_H = 25
    im = Image.new('RGBA',(IMG_W ,IMG_H),'#efefef')

    mp = hashlib.md5()
    mp_src = mp.update(str(datetime.now()))
    mp_src = mp.hexdigest()
    rand_str = mp_src[0:4]
    
    img_text0 =  Image.new('RGBA',(IMG_W/4,IMG_H))   
    draw0 = ImageDraw.Draw(img_text0)
    draw0.text((0,0), rand_str[0], font=ImageFont.truetype(_font_file, random.randrange(16,20)),fill=(0,255,0))   
    del draw0
    
    img_text1 =  Image.new('RGBA',(IMG_W/4,IMG_H))    
    draw1 = ImageDraw.Draw(img_text1)
    draw1.text((0,0), rand_str[1], font=ImageFont.truetype(_font_file, random.randrange(16,20)),fill=(random.randrange(0,255),random.randrange(0,255),random.randrange(0,255)))   
    del draw1
    
    draw = ImageDraw.Draw(im)
    im.paste(img_text0,(0,0,img_text0.size[0],img_text0.size[1]),img_text0)
    im.paste(img_text1,(20,0,20+img_text1.size[0],img_text1.size[1]),img_text1)
    
    draw.text((40,0), rand_str[2], font=ImageFont.truetype(_font_file, random.randrange(16,20)),fill=(random.randrange(0,255),random.randrange(0,255),random.randrange(0,255)))   
    draw.text((60,0), rand_str[3], font=ImageFont.truetype(_font_file, random.randrange(16,20)),fill=(random.randrange(0,255),random.randrange(0,255),random.randrange(0,255)))   
    del draw   
    buf = cStringIO.StringIO()
    im.save(buf, 'png')
    
    li = [rand_str.lower(), buf]
    return li


def get_current_datetime():
    '''获取当前时间,格式:yyyy-mm-dd hh24:mi:ss'''
    now = time.localtime(time.time())
    return time.strftime('%Y-%m-%d %H:%M:%S', now)

def ip2locate(ipv4=None):
    '''
    将传入IP通过sina接口查询出IP的所在城市，直接返回所在城市，没有找到城市的，默认返回武汉,
    目前仅能处理ipv4格式的IP
    '''
    if ipv4 is None or ipv4=='127.0.0.1' : return "武汉"
    url = "http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=%s" % ipv4
    try:
        html = urllib.urlopen(url)
        content = json.loads(html.read(), "utf-8")
        return content["city"]
#        print 'city :', content['city']
#        print 'ret :', content['ret']
#        print 'start :', content['start']
#        print 'end :', content['end']
#        print 'country :', content['country']
#        print 'province :', content['province']
#        print 'district :', content['district']
#        print 'isp :', content['isp']
#        print 'type :', content['type']
#        print 'desc :', content['desc']
    except IOError,io:
        print io.strerror
    except Exception,e:
        print e


def locate2host(locate=None):
    '''
    locate:通过ip2locate函数获取用户所在的城市中文名称;
    传递到此函数中获取对应的主机域名,如伟入'武汉'-->返回wh.ilouwai.com
    '''
    from constants import locate_host
    if locate is None:
        return locate_host["武汉"]
    else:
        host = locate_host[locate]
        if host is not None:
            return host
        return locate_host["武汉"]

def ip2host(ipv4=None):
    '''此函数是ip2locate与locate2host的综合'''
    return locate2host(ip2locate(ipv4))

if __name__ ==  "__main__":
    pass